<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>AI渗透综合测试平台</title>
    <style>
        :root {
            --primary: #3498db;
            --success: #2ecc71;
            --danger: #e74c3c;
            --warning: #f39c12;
            --dark: #2c3e50;
            --light: #ecf0f1;
        }

        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background-color: #f5f7fa;
            color: #333;
            line-height: 1.6;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        header {
            background: linear-gradient(135deg, var(--dark), #1a2530);
            color: white;
            padding: 20px 0;
            text-align: center;
            border-radius: 0 0 10px 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            margin-bottom: 30px;
        }

        header h1 {
            margin-bottom: 10px;
        }

        .card {
            background: white;
            border-radius: 10px;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
            padding: 25px;
            margin-bottom: 30px;
            transition: transform 0.3s, box-shadow 0.3s;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
        }

        .card h2 {
            color: var(--dark);
            margin-bottom: 20px;
            padding-bottom: 10px;
            border-bottom: 2px solid var(--light);
        }

        .btn {
            display: inline-block;
            padding: 10px 20px;
            margin: 5px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s;
            text-align: center;
        }

        .btn-primary {
            background-color: var(--primary);
            color: white;
        }

        .btn-success {
            background-color: var(--success);
            color: white;
        }

        .btn-danger {
            background-color: var(--danger);
            color: white;
        }

        .btn:hover {
            opacity: 0.9;
            transform: scale(1.05);
        }

        .target-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 15px;
        }

        .target-card {
            background: var(--light);
            padding: 15px;
            border-radius: 8px;
            text-align: center;
        }

        .target-card h3 {
            color: var(--dark);
            margin-bottom: 10px;
        }

        .instance {
            background: #f8f9fa;
            border-left: 4px solid var(--primary);
            padding: 15px;
            margin: 15px 0;
            border-radius: 5px;
        }

        .instance.completed {
            border-left-color: var(--success);
        }

        .timer {
            font-size: 1.5rem;
            font-weight: bold;
            color: var(--danger);
            margin: 10px 0;
            font-family: monospace;
        }

        .key-input {
            padding: 10px;
            width: 300px;
            border: 2px solid #ddd;
            border-radius: 5px;
            margin-right: 10px;
            font-size: 1rem;
        }

        .key-input:focus {
            border-color: var(--primary);
            outline: none;
        }

        .status-badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: bold;
            margin-left: 10px;
        }

        .status-running {
            background-color: rgba(52, 152, 219, 0.2);
            color: var(--primary);
        }

        .status-stopped {
            background-color: rgba(231, 76, 60, 0.2);
            color: var(--danger);
        }

        footer {
            text-align: center;
            margin-top: 40px;
            padding: 20px;
            color: #7f8c8d;
            border-top: 1px solid #eee;
        }

        .no-instances {
            text-align: center;
            padding: 30px;
            color: #7f8c8d;
        }
    </style>
</head>
<body>
<header>
    <div class="container">
        <h1>AI渗透综合测试平台</h1>
        <p>练习网络安全技能，挑战各种漏洞场景</p>
    </div>
</header>

<div class="container">
    <!-- 靶场选择区域 -->
    <div class="card">
        <h2>选择挑战靶场</h2>
        <div class="target-grid">
            <div class="target-card">
                <h3>CISP靶场</h3>
                <p>包含多个服务的综合安全挑战</p>
                <button class="btn btn-primary" onclick="startTarget('cisp')">启动挑战</button>
            </div>
            <div class="target-card">
                <h3>综合靶场</h3>
                <p>包含多个服务的综合安全挑战</p>
                <button class="btn btn-primary" onclick="startTarget('syn')">启动挑战</button>
            </div>
            <div class="target-card">
                <h3>密码学挑战</h3>
                <p>加密算法分析与攻击</p>
                <button class="btn btn-primary" onclick="alert('更多靶场正在开发中...')">即将上线</button>
            </div>
            <div class="target-card">
                <h3>逆向工程</h3>
                <p>软件逆向与破解技术</p>
                <button class="btn btn-primary" onclick="alert('更多靶场正在开发中...')">即将上线</button>
            </div>
        </div>
    </div>

    <!-- 活动实例区域 -->
        <div class="card">
            <h2>我的挑战实例
                <span class="status-badge status-running">运行中: <span id="running-count">0</span></span>
                <span class="status-badge status-stopped">已完成: <span id="completed-count">0</span></span>
            </h2>
            <div id="active-containers">
                {% for container in running_containers %}
                <div class="instance" id="container-{{ container.id }}">
                    <div style="display: flex; justify-content: space-between; align-items: center;">
                        <h3>{{ get_target_display_name(container.name) }}
                            <span class="status-badge status-running">运行中</span>
                        </h3>
                        <small>实例ID: {{ container.id[:8] }}</small>
                    </div>
                    <div class="timer" id="timer-{{ container.id }}">01:00:00</div>

                    <div style="margin: 15px 0;">
                        <h4>服务访问地址：</h4>
                        {% for cport, hport in container.ports.items() %}
                            {% if container.name == 'cisp' %}
                                {% set service_names = {
                                    '81/tcp': '第一关',
                                    '82/tcp': '第二关',
                                    '83/tcp': '第三关',
                                    '84/tcp': '第四关',
                                    '85/tcp': '第五关'
                                } %}
                                <p><strong>{{ service_names.get(cport, '服务') }}</strong> →
                                   <a href="http://192.168.88.66:{{ hport }}" target="_blank">访问 ({{ hport }})</a>
                                </p>
                            {% else %}
                                <p><strong>端口 {{ cport.split('/')[0] }}</strong> →
                                   <a href="http://192.168.88.66:{{ hport }}" target="_blank">访问服务 ({{ hport }})</a>
                                </p>
                            {% endif %}
                        {% endfor %}
                    </div>

                    <div style="display: flex; align-items: center; margin-top: 15px;">
                        <input type="text" class="key-input" id="key-{{ container.id }}" placeholder="输入Flag/Key">
                        <button class="btn btn-success" onclick="submitKey('{{ container.id }}')">提交验证</button>
                        <button class="btn btn-danger" onclick="stopContainer('{{ container.id }}')" style="margin-left: 10px;">停止挑战</button>
                    </div>
                </div>
                {% else %}
                <div class="no-instances">
                    <h3>暂无运行中的挑战</h3>
                    <p>请从上方选择一个靶场开始挑战</p>
                </div>
                {% endfor %}
            </div>
        </div>
    </div>

<footer>
    <div class="container">
        <p>AI渗透综合测试平台 &copy; 2025 | 基于 Docker 和 Flask 构建</p>
    </div>
</footer>

<script>
    // 页面加载完成后初始化计时器
        document.addEventListener('DOMContentLoaded', function() {
            // 为每个已存在的容器启动计时器
            const instances = document.querySelectorAll('.instance');
            instances.forEach(instance => {
                const containerId = instance.id.replace('container-', '');
                startTimer(containerId, 3600);
            });
            updateStats();
        });
    // 启动靶场
    function startTarget(targetName) {
        const button = event.target;
        button.disabled = true;
        button.textContent = '启动中...';

        fetch('/start_target', {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: `target=${targetName}`
        })
            .then(res => res.json())
            .then(data => {
                button.disabled = false;
                button.textContent = '启动挑战';

                if (data.error) {
                    alert(`错误: ${data.error}`);
                } else {
                    addActiveContainer(data.id, targetName, data.ports);
                    updateStats();
                }
            })
            .catch(error => {
                button.disabled = false;
                button.textContent = '启动挑战';
                alert(`请求失败: ${error.message}`);
            });
    }

    // 添加活动容器显示
    function addActiveContainer(containerId, targetName, ports) {
        // 移除"暂无实例"提示
        const noInstances = document.querySelector('.no-instances');
        if (noInstances) noInstances.remove();

        // 检查是否已存在
        if (document.getElementById(`container-${containerId}`)) {
            return;
        }
        const container = document.createElement('div');
        container.className = 'instance';
        container.id = `container-${containerId}`;

        let portsHtml = '';
        if (targetName === 'cisp') {
            const serviceNames = {
                '81/tcp': '第一关',
                '82/tcp': '第二关',
                '83/tcp': '第三关',
                '84/tcp': '第四关',
                '85/tcp': '第五关'
            };

            for (const [cport, hport] of Object.entries(ports)) {
                const portNum = cport.split('/')[0];
                const serviceName = serviceNames[cport] || `服务${portNum}`;
                portsHtml += `<p><strong>${serviceName}</strong> → <a href="http://192.168.88.66:${hport}" target="_blank">访问 (${hport})</a></p>`;
            }
        } else {
            for (const [cport, hport] of Object.entries(ports)) {
                const portNum = cport.split('/')[0];
                portsHtml += `<p><strong>端口 ${portNum}</strong> → <a href="http://192.168.88.66:${hport}" target="_blank">访问服务 (${hport})</a></p>`;
            }
        }

        container.innerHTML = `
                <div style="display: flex; justify-content: space-between; align-items: center;">
                    <h3>${getTargetDisplayName(targetName)}
                        <span class="status-badge status-running">运行中</span>
                    </h3>
                    <small>实例ID: ${containerId.slice(0, 8)}</small>
                </div>
                <div class="timer" id="timer-${containerId}">01:00:00</div>

                <div style="margin: 15px 0;">
                    <h4>服务访问地址：</h4>
                    ${portsHtml}
                </div>

                <div style="display: flex; align-items: center; margin-top: 15px;">
                    <input type="text" class="key-input" id="key-${containerId}" placeholder="输入Flag/Key">
                    <button class="btn btn-success" onclick="submitKey('${containerId}')">提交验证</button>
                    <button class="btn btn-danger" onclick="stopContainer('${containerId}')" style="margin-left: 10px;">停止挑战</button>
                </div>
            `;

        document.getElementById('active-containers').prepend(container);
        startTimer(containerId, 3600);  // 1小时倒计时
        updateStats();
    }

    // 获取靶场显示名称
    function getTargetDisplayName(targetName) {
        const names = {
            'cisp': 'CISP靶场',
            'syn': '综合靶场'
        };
        return names[targetName] || targetName;
    }

    // 倒计时功能
        function startTimer(containerId, totalSeconds) {
            const timerElem = document.getElementById(`timer-${containerId}`);
            if (!timerElem) return;

            const startTime = Date.now();
            const endTime = startTime + totalSeconds * 1000;

            const timer = setInterval(() => {
                const now = Date.now();
                const remaining = Math.max(0, Math.floor((endTime - now) / 1000));

                const hrs = Math.floor(remaining / 3600);
                const mins = Math.floor((remaining % 3600) / 60);
                const secs = remaining % 60;

                timerElem.textContent = `${hrs.toString().padStart(2, '0')}:${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;

                if (remaining <= 0) {
                    clearInterval(timer);
                    const containerElem = document.getElementById(`container-${containerId}`);
                    if (containerElem) {
                        containerElem.querySelector('.status-badge').className = 'status-badge status-stopped';
                        containerElem.querySelector('.status-badge').textContent = '已过期';
                    }
                }
            }, 1000);
        }

        // 提交Key
        function submitKey(containerId) {
            const keyInput = document.getElementById(`key-${containerId}`);
            const key = keyInput.value.trim();

            if (!key) {
                alert("请输入Flag/Key");
                return;
            }

            const submitBtn = event.target;
            submitBtn.disabled = true;
            submitBtn.textContent = '验证中...';

            fetch('/submit_key', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `container_id=${containerId}&key=${encodeURIComponent(key)}`
            })
            .then(res => res.json())
            .then(data => {
                submitBtn.disabled = false;
                submitBtn.textContent = '提交验证';

                if (data.valid) {
                    const containerElem = document.getElementById(`container-${containerId}`);
                    if (containerElem) {
                        containerElem.innerHTML = `
                            <div style="text-align: center; padding: 30px;">
                                <h3 style="color: var(--success);">挑战成功！</h3>
                                <p>恭喜你完成了 ${containerElem.querySelector('h3').textContent.split(' ')[0]} 挑战</p>
                                <p>✅ Flag验证正确</p>
                                <button class="btn btn-primary" onclick="this.parentElement.parentElement.remove(); updateStats();">关闭</button>
                            </div>
                        `;
                    }
                } else {
                    alert("Flag验证失败，请重新尝试");
                }
            })
            .catch(error => {
                submitBtn.disabled = false;
                submitBtn.textContent = '提交验证';
                alert(`验证失败: ${error.message}`);
            });
        }

        // 停止容器
        function stopContainer(containerId) {
            if (!confirm("确定要停止此挑战吗？未完成的进度将会丢失！")) return;

            const stopBtn = event.target;
            stopBtn.disabled = true;
            stopBtn.textContent = '停止中...';

            fetch('/stop_target', {
                method: 'POST',
                headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                body: `container_id=${containerId}`
            })
            .then(() => {
                const elem = document.getElementById(`container-${containerId}`);
                if (elem) elem.remove();
                updateStats();
            })
            .catch(error => {
                stopBtn.disabled = false;
                stopBtn.textContent = '停止挑战';
                alert(`停止失败: ${error.message}`);
            });
        }

        // 更新统计信息
        function updateStats() {
            const instances = document.querySelectorAll('.instance');
            document.getElementById('running-count').textContent = instances.length;

            // 在实际应用中，可以从服务器获取已完成数量
            // 这里仅做演示
            document.getElementById('completed-count').textContent = "0";
        }
    </script>
</body>
</html>